package sysytmRepo

import (
	"gorm.io/gorm"
	"ruoyi/domain/entity/common"
	"ruoyi/domain/entity/response"
	"ruoyi/domain/entity/system"
	"ruoyi/domain/repository"
	"ruoyi/utils"
)

type SysPostRepo struct {
	db *gorm.DB
}

func SysPostRepository(db *gorm.DB) *SysPostRepo {
	return &SysPostRepo{db}
}

var _ repository.SysPostRepository = &SysPostRepo{}

func (r *SysPostRepo) SelectUserPostGroup(userName string) string {
	var posts []system.SysPost
	var result = ""
	r.db.Raw("select p.post_id, p.post_name, p.post_code "+
		"from sys_post p "+
		"left join sys_user_post up on up.post_id = p.post_id "+
		"left join sys_user u on u.user_id = up.user_id "+
		"where u.user_name = ?", userName).Scan(&posts)
	if posts != nil {
		for i := range posts {
			sysPost := posts[i]
			if i == 0 {
				result = sysPost.PostName
			} else {
				result += "," + sysPost.PostName
			}
		}
	}
	return result
}

// 分页查询
func (r *SysPostRepo) SelectSysPostList(params common.SearchTableDataParam, isPage bool) common.TableDataInfo {

	var pageNum = params.PageNum
	var pageSize = params.PageSize
	sysPost := params.Other.(system.SysPost)

	offset := (pageNum - 1) * pageSize
	var total int64
	var rows []system.SysPost

	var db = r.db.Model(&rows)

	var postCode = sysPost.PostCode
	if postCode != "" {
		db.Where("post_code like ?", "%"+postCode+"%")
	}
	var status = sysPost.Status
	if status != "" {
		db.Where("status = ?", status)
	}
	var postName = sysPost.PostName
	if postName != "" {
		db.Where("post_name like ?", "%"+postName+"%")
	}

	db.Order("post_sort")

	if err := db.Count(&total).Error; err != nil {
		return common.Fail()
	}
	if isPage {
		if err := db.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
			return common.Fail()
		}
	} else {
		if err := db.Find(&rows).Error; err != nil {
			return common.Fail()
		}
	}

	if rows == nil {
		return common.Fail()
	} else {
		return common.Success(rows, total)
	}
}

func (r *SysPostRepo) SelectPostListByUserId(userId int) []int {
	var result []int
	r.db.Raw("select p.post_id "+
		"from sys_post p "+
		"left join sys_user_post up on up.post_id = p.post_id "+
		"left join sys_user u on u.user_id = up.user_id "+
		"where u.user_id = ? ", userId).Find(&result)
	return result
}

/*
*添加 岗位和用户关联
 */
func (r *SysPostRepo) AddPostByUser(user system.SysUserParam) {
	postIds := user.PostIds
	userId := user.UserId
	r.AddPostListByUser(postIds, userId)
}

func (r *SysPostRepo) AddPostListByUser(postIds []int, userId int) {
	var posts []system.SysUserPost
	for i := 0; i < len(postIds); i++ {
		var post = system.SysUserPost{
			PostId: postIds[i],
			UserId: userId,
		}
		posts = append(posts, post)
	}
	err := r.db.CreateInBatches(posts, len(posts)).Error
	if err != nil {
		panic(response.ReturnFailMsg("添加 部门管理用户失败"))
	}
}

// 删除关联用户
func (r *SysPostRepo) DeletePostByUser(userIds []int) {
	err := r.db.Exec("delete from sys_user_post where user_id in (?) ", userIds).Error
	if err != nil {
		panic(response.ReturnFailMsg("删除部门关联用户失败"))
	}
}

func (r *SysPostRepo) FindPostInfoById(postId string) system.SysPost {
	var post system.SysPost
	err := r.db.Where("post_id = ?", postId).First(&post).Error
	if err != nil {
		panic(response.ReturnFailMsg(err.Error()))
	}
	return post
}

func (r *SysPostRepo) SavePost(post system.SysPost) response.Response {
	err := r.db.Model(&system.SysPost{}).Create(&post).Error
	if err != nil {
		return response.ReturnFailMsg(err.Error())
	}
	return response.ReturnSuccess("操作成功")
}

func (r *SysPostRepo) EditPost(sysPost system.SysPost) response.Response {
	err := r.db.Updates(&sysPost).Error
	if err != nil {
		return response.ReturnFailMsg(err.Error())
	}
	return response.ReturnSuccess("操作成功")
}

func (r *SysPostRepo) DeletePost(postIds string) response.Response {
	err := r.db.Where("post_id in (?)", utils.Split(postIds)).Delete(&system.SysPost{}).Error
	if err != nil {
		return response.ReturnFailMsg(err.Error())
	}
	return response.ReturnSuccess("操作成功")
}
